import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import {
	login,
	logout,
	getInfo
} from '@/api/login'
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth'

const baseUrl = config.baseUrl

const user = {
	state: {
		token: getToken(),
		name: storage.get(constant.name),
		avatar: storage.get(constant.avatar),
		id: storage.get(constant.id),
		phone:storage.get(constant.phone)
	},

	mutations: {
		SET_ID: (state, userId) => {
			state.id = userId
			storage.set(constant.id, userId)
		},
		SET_TOKEN: (state, token) => {
			state.token = token
			setToken(token)
		},
		SET_NAME: (state, name) => {
			state.name = name
			storage.set(constant.name, name)
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
			storage.set(constant.avatar, avatar)
		},
		SET_PHONE: (state, phone) => {
			state.phone = phone
			storage.set(constant.phone, phone)
		}
	},

	actions: {
		// 登录
		async Login({
			commit,
			dispatch
		}, code) {
			const res = await login(code)
			commit('SET_TOKEN', res.token)
		},

		// 获取用户信息
		GetInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				getInfo().then(res => {

					const {
						id,
						avatarUrl,
						nickname,
						phone
					} = res.user
					// console.log()
					const avatar = (avatarUrl == "" || avatarUrl == null) ?
						require("@/static/images/profile.jpg") : avatarUrl
					const username = (nickname == "" || nickname ==
						null) ? "" : nickname
					commit('SET_ID', id)
					commit('SET_NAME', username)
					commit('SET_AVATAR', avatar)
					commit('SET_PHONE',phone)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 退出系统
		LogOut({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				logout(state.token).then(() => {
					commit('SET_TOKEN', '')
					removeToken()
					storage.clean()
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		}
	}
}

export default user